<?php
namespace App\Libs\wrapper;
use Illuminate\Support\Facades\DB;
use App\Libs\wrapper\Comm;
class Index extends Comm
{
    /**
     * @desc 获取首页渲染数据
     * @param $UserID
     * @return mixed
     */
    public function get_index_data($UserID){
        $sql = "select a.groupid,a.NickName,a.ImageUrl,b.Name as comname,c.Name as groupname,a.UserID,a.companyID,a.superadmin 
                    from usersys as a
                    left  join companysys as b ON a.companyID=b.CompanyID 
                    left join groupsys as c on a.groupid=c.GroupID 
                    where a.UserID={$UserID}";
        $user = DB::select($sql);
        $user = $this->object_array($user[0]);
        $check = substr($user['ImageUrl'],0,4);
        if($check != "http"){
            //$user['ImageUrl'] = "http://".$_SERVER['HTTP_HOST']."/Uploads/".$user['ImageUrl'];
			$user['ImageUrl'] = "http://".$_SERVER['HTTP_HOST']."/lcx/images/timg1.jpg";
        }
        return $user;
    }

    /**
     * @desc 获取后台首页菜单
     * @param $UserID
     * @param $groupid
     * @param $superadmin
     * @return array
     */
    public function menuinfo($UserID,$groupid,$superadmin){
        if($superadmin == "yes"){
            if($groupid == 2){
                $groupid = 10;
            }else if($groupid == 3){
                $groupid = 12;
            }else if($groupid == 4){
                $groupid = 11;
            }

            $sql = "select PersID,fid from group_pers where GroupID={$groupid} and fid!=0";

            $arr = DB::select($sql);
            $arr = $this->object_array($arr);
        }else{
            $comtype = session("userinfo.comtype");
            if($comtype == '1'){
                $fgid = 10;
            }else if($comtype == '3'){
                $fgid = 12;
            }else if($comtype == '2'){
                $fgid = 11;
            }else{
                $fgid = 1;
            }
            $sql = "select PersID,fid from user_pers where UserID={$UserID} and fid!=0 and `type`=1
					UNION
					select gp.PersID,gp.fid from group_pers as gp inner join (
					select PersID,fid from user_pers where UserID={$UserID} and fid!=0 and `type`=2)
					as up on gp.PersID=up.PersID where gp.groupid={$groupid}
					UNION
					select gp.PersID,gp.fid from group_pers as gp inner join (
						select PersID,fid from user_pers where UserID={$UserID} and fid!=0 and `type`=3
						UNION
						select rp.PersID,rp.fid from users_role as ur left join roles_pers as rp on ur.RolesID=rp.RolesID and rp.fid!=0 and ur.UserID={$UserID}
					) as up on gp.PersID=up.PersID where gp.groupid={$fgid}";
            $arr = DB::select($sql);
            $arr = $this->object_array($arr);
        }
        $perinfo = array();
        foreach($arr as $k => $v){
            if($v['fid'] > 0){
                $sql = "select a.*,b.name as fid,b.sort as sort,b.icon as icon from permission1 as a
					left join permission1 as b on b.PermissionID=a.fid where a.PermissionID={$v['PersID']} and a.peroper=1";

                $info = DB::select($sql);
                $info = $this->object_array($info);
                if($info){
                    $perinfo[] = $info[0];
                }

            }else{
                $sql = "select a.*,b.name as fid,b.sort as sort,b.icon as icon from group_pers as gp 
						left join permission1 as a on gp.PersID=a.PermissionID 
						left join permission1 as b on a.fid=b.PermissionID 
						where gp.fid={$v['PersID']} and gp.groupid={$groupid} and a.peroper=1";

                $info = DB::select($sql);
                $info = $this->object_array($info);
                foreach($info as $vo){
                    $perinfo[] = $vo;
                }
            }
        }
        $menu = array();
        foreach($perinfo as $k=>$v){
            $menu[$v['fid']]['name']=$v['fid'];
            $menu[$v['fid']]['sort']=$v['sort'];
            $menu[$v['fid']]['icon']=$v['icon'];
            $menu[$v['fid']]['nodes'][$k]['name']=$v['name'];
            $menu[$v['fid']]['nodes'][$k]['controller']=$v['controller'];
            $menu[$v['fid']]['nodes'][$k]['methods']=$v['methods'];
        }
        foreach($menu as $v){
            if($v['sort']){
                $sort[]=$v["sort"];
            }
        }
        //if(count($menu)>0){
        //  array_multisort($sort,SORT_ASC,$menu);
        //}
        return $menu;
    }


    /**
     * @desc 获取企业数据统计
     * @param $comid
     * @return mixed
     */
    public function get_property_report($comid){
        $arr['allreport'] = $this->get_property_report_all($comid);
        $arr['typereport'] = $this->get_property_report_type($comid);
        $arr['depreport'] = $this->get_property_report_deps($comid);
        return $arr;
    }


    /**
     * @desc 获取首页列表数据
     * @param $comid
     * @param $num
     * @return mixed
     */
    public function get_property_oprate_list($comid,$num){
		$arr['use_list'] = $this->get_use_wait_list($comid,$num);
        $arr['borrow_list'] = $this->get_borrow_wait_list($comid,$num);
        $arr['apply_list'] = $this->get_apply_wait_list($comid,$num);
        $arr['inventory_list'] = $this->get_inventory_wait_list($comid,$num);
        return $arr;
    }


    /**
     * @desc 获取企业资产概况数据
     * @param $comid
     * @return int
     */
    public function get_property_report_all($comid){
        $sql = "select count(1) as xz,ifnull(sum(price),0) as allprice from pro_propertys where comp_id = {$comid} and p_state = 1";
        $xz = DB::select($sql);

        $sql = "select count(1) as zy,ifnull(sum(price),0) as allprice from pro_propertys where comp_id = {$comid} and p_state in (2,3,4,5)";
        $zy = DB::select($sql);
		
		$sql = "select count(1) as bf,ifnull(sum(price),0) as allprice from pro_propertys where comp_id = {$comid} and p_state =6";
        $bf = DB::select($sql);
		
        if($xz && $zy){
            $xz = $this->object_array($xz)[0];
            $zy = $this->object_array($zy)[0];
            $bf = $this->object_array($bf)[0];

            $arr[0]['value'] = $zy['zy'];
            $arr[0]['name'] = '在用';
            $arr[0]['price'] = $zy['allprice'];
			
            $arr[1]['value'] = $xz['xz'];
            $arr[1]['name'] = '闲置';
            $arr[1]['price'] = $xz['allprice'];
			
            $arr[2]['value'] = $bf['bf'];
            $arr[2]['name'] = '报废';
            $arr[2]['price'] = $bf['allprice'];
            return $arr;
        }else{
            return 0;
        }


    }


    /**
     * @desc 获取企业资产分类占比
     * @param $comid
     * @return int|mixed
     */
    public function get_property_report_type($comid){
        $sql = "select count(1) as typenum,ppt.Id,ppt.type_name from pro_propertys as pp left join pro_property_type as ppt on ppt.Id = pp.propertytype_id 
                where pp.comp_id = {$comid} group by pp.propertytype_id limit 10";
        $res = DB::select($sql);
        if($res){
            $res = $this->object_array($res);
            return $res;
        }else{
            return 0;
        }
    }


    /**
     * @desc 获取各个部门资产统计
     * @param $comid
     * @return int|mixed
     */
    public function get_property_report_deps($comid){
        $sql = "select DepartID,`Name` from departsys where ComID = {$comid} limit 5";
        $deps = DB::select($sql);
        if($deps){
            $deps = $this->object_array($deps);
            for($i=0;$i<count($deps);$i++){
                $sql = "select count(1) as num from pro_propertys as pp left join departsys as d on d.DepartID = pp.use_dept 
                        where pp.comp_id = {$comid} and use_dept = {$deps[$i]['DepartID']} and use_dept is not null";
                $res = DB::select($sql);
                if($res === false){
                    return 0;
                }
                $res = $this->object_array($res)[0];
                $deps[$i]['num'] = $res['num'];
            }
            return $deps;
        }else{
            return 0;
        }
    }
	
	/**
	 * @desc 获取领用用待审核列表数据
	 * @param $comid
	 * @param $num
	 * @return int|mixed
	 */
	public function get_use_wait_list($comid,$num){
		$sql = "select pu.*,
					if(pu.user_id!='',(select `NickName` from usersys where UserID=pu.user_id),'') as use_nickname,
					if(pu.warehouse_after!='',(select area_name from pro_warehouse where Id=pu.warehouse_after),'') as area_name,
					if(pu.dept_after!='',(select `Name` from departsys where DepartID=pu.dept_after),'') as dept_name 
					from pro_property_use pu 
					where pu.comp_id = {$comid} and pu.state = 1 
					order by pu.Id desc 
					limit {$num}";
	    $res = DB::select($sql);
	    if($res){
	        $res = $this->object_array($res);
	        return $res;
	    }else{
	        return 0;
	    }
	}


    /**
     * @desc 获取借用待审核列表数据
     * @param $comid
     * @param $num
     * @return int|mixed
     */
    public function get_borrow_wait_list($comid,$num){
        $sql = "select ppb.Id,ppb.borrow_sn,ppb.borrow_time,ppb.estimate_back_time,ppb.`desc`,u.NickName from pro_property_borrow as ppb left join usersys as u on 
                u.UserID = ppb.use_user where ppb.comp_id = {$comid} and ppb.state = 1 limit {$num}";
        $res = DB::select($sql);
        if($res){
            $res = $this->object_array($res);
            return $res;
        }else{
            return 0;
        }
    }


    /**
     * @desc 获取申请调拨审核列表数据
     * @param $comid
     * @return array|int
     */
    public function get_apply_wait_list($comid,$num){
        $sql = "select ppa.*,c.Name,u.NickName from pro_property_apply as ppa left join companysys as c on ppa.comp_id = c.CompanyID left join usersys as u on u.UserID = ppa.user_id
                where ppa.comp_id = {$comid} and ppa.apply_state = 1 limit {$num}";
        $res = DB::select($sql);
        if($res){
            $res = $this->object_array($res);
            return $res;
        }else{
            return 0;
        }
    }


    /**
     * @desc 获取盘点任务-列表
     */
    public function get_inventory_wait_list($comid,$num){
        $sql = "select ppi.Id,ppi.inventory_sn,ppi.desc,ppi.is_contain_allocation,u1.NickName as inventory_user,u2.NickName as establish_user,
                ppi.add_start_time,ppi.add_end_time,ppi.state,ppi.create_time  from pro_property_inventory as ppi left join usersys as u1 on u1.UserID = 
                ppi.inventory_user left join usersys as u2 on u2.UserID = ppi.establish_user where ppi.comp_id = {$comid} and ppi.state = 1 order by ppi.Id 
                desc limit {$num}";
        $res = DB::select($sql);
        if($res){
            $res = $this->object_array($res);
            return $res;
        }else{
            return 0;
        }
    }


    /**
     * @desc 获取个人借用/领用数量
     * @param $userid
     * @return mixed
     */
    public function get_user_property_count($userid){
        $sql = "select count(1) as num from pro_propertys where use_user = {$userid} and p_state = 2";
        $ly = DB::select($sql);
        if($ly){
            $ly = $this->object_array($ly)[0];
            $arr['ly'] = $ly['num'];
        }
        $sql = "select count(1) as num from pro_propertys where use_user = {$userid} and p_state = 3";
        $jy = DB::select($sql);
        if($jy){
            $jy = $this->object_array($jy)[0];
            $arr['jy'] = $jy['num'];
        }
        return $arr;
    }


    /**
     * @desc 获取部门资产概况
     * @param $depid
     * @return int
     */
    public function get_deps_property_state($depid){
        $sql = "select count(1) as xz,ifnull(sum(price),0) as allprice from pro_propertys where use_dept = {$depid} and use_user is null";
        $xz = DB::select($sql);

        $sql = "select count(1) as zy,ifnull(sum(price),0) as allprice from pro_propertys where use_dept = {$depid} and use_user is not null";
        $zy = DB::select($sql);
        if($xz && $zy){
            $xz = $this->object_array($xz)[0];
            $zy = $this->object_array($zy)[0];

            $arr[0]['value'] = $zy['zy'];
            $arr[0]['name'] = '在用';
            $arr[0]['price'] = $zy['allprice'];
            
            $arr[1]['value'] = $xz['xz'];
            $arr[1]['name'] = '闲置';
            $arr[1]['price'] = $xz['allprice'];

            return $arr;
        }else{
            return 0;
        }
    }


    /**
     * @desc 获取部门资产分类统计
     * @param $depid
     * @return int|mixed
     */
    public function get_deps_property_type($depid){
        $sql = "select count(1) as typenum,ppt.Id,ppt.type_name from pro_propertys as pp left join pro_property_type as ppt on ppt.Id = pp.propertytype_id 
                where pp.use_dept = {$depid} group by pp.propertytype_id limit 10";
        $res = DB::select($sql);
        if($res){
            $res = $this->object_array($res);
            return $res;
        }else{
            return 0;
        }
    }


    /**
     * @desc 获取部门/用户在用资产列表
     * @param $objid
     * @param $type(1部门2用户)
     * @return int|mixed
     */
    public function get_inuse_property_list($objid,$type){
        if($type = 1){
            $sql = "select * from pro_propertys as pp left join pro_property_type as ppt on ppt.Id = pp.propertytype_id left join pro_property_brand as ppb on 
                pp.brand_id = ppb.Id where pp.use_dept = {$objid} and pp.use_user is not null";
            $res = DB::select($sql);
            if($res){
                $res = $this->object_array($res);
                return $res;
            }else{
                return 0;
            }
        }else{
            $sql = "select * from pro_propertys as pp left join pro_property_type as ppt on ppt.Id = pp.propertytype_id left join pro_property_brand as ppb on 
                pp.brand_id = ppb.Id where pp.use_user = {$objid}";
            $res = DB::select($sql);
            if($res){
                $res = $this->object_array($res);
                return $res;
            }else{
                return 0;
            }
        }
    }


    /**
     * @desc 获取用户/部门盘点单列表
     * @param $userid
     * @return array
     */
    public function get_user_inventory($userid){
        $sql = "select ppi.Id,ppi.inventory_sn,ppi.desc,ppi.is_contain_allocation,u1.NickName as inventory_user,u2.NickName as establish_user,
                ppi.add_start_time,ppi.add_end_time,ppi.state,ppi.create_time  from pro_property_inventory as ppi left join usersys as u1 on u1.UserID = 
                ppi.inventory_user left join usersys as u2 on u2.UserID = ppi.establish_user where inventory_user = {$userid}";
        $result = DB::select($sql);
        if($result){
            $result = $this->object_array($result);
            return $result;
        }else{
            return 0;
        }
    }
	
	/**
     * @desc 获取企业列表
     * @param comname
     * @return list
     */
    public function get_company_list($comname){
        $sql = "select * from companysys where Name like '%{$comname}%'";
        $res = DB::select($sql);
        if($res){
            $res = $this->object_array($res);
            return $res;
        }else{
            return 0;
        }
    }


    /**
     * @desc 申请加入企业
     * @param $userinfo
     * @param $data
     * @return int
     */
    public function join_com_apply($userinfo,$data){
        DB::beginTransaction();
        //判断是否已加入企业
        $sql = "select * from usersys where UserID = {$userinfo['UserID']} and State = 1";
        $user = DB::select($sql);
        if($user){
            $user = $this->object_array($user);
            if(!empty($user['companyID'])){
                return 2;
                DB::rollback();
            }
        }else{
            return 3;
            DB::rollback();
        }
        //判断是否申请加入企业
        $sql = "select * from pro_apply_join where user_id = {$userinfo['UserID']} and state = 1 and `type` = 1";
        $join = DB::select($sql);
        if($join){
            $join = $this->object_array($join)[0];
            if(!empty($join['Id'])){
                return 4;
                DB::rollback();
            }
        }
        //判断是否申请认证
        $sql = "select * from company_attestation where user_id = {$userinfo['UserID']} and state = 1";
        $com = DB::select($sql);
        if($com){
            $com = $this->object_array($com)[0];
            if(!empty($com['Id'])){
                return 5;
                DB::rollback();
            }
        }
        //获取企业管理员
        $sql = "select * from usersys where companyID = {$data['comid']} and groupid = 2";
        $info = DB::select($sql);
        if($info){
            $info = $this->object_array($info);
        }

        //插入申请记录
        $time = date("Y-m-d H:i:s",time());
        $sql = "insert into pro_apply_join (`user_id`,`company_id`,`state`,`create_time`) values ({$userinfo['UserID']},{$data['comid']},1,'{$time}')";
        $res = DB::insert($sql);
        if(!$res){
            return 6;
        }
		$id = DB::getPdo()->lastInsertId();

        //给管理员发送消息
        for($i=0;$i<count($info);$i++){
            $newtime = date("Y-m-d h:i:s",time());
            //发送消息
            $title = "有用户申请加入您的企业，请及时处理";
            $content = "{$userinfo['NickName']} 申请加入企业,是否同意？";
            $sql = "insert into pro_property_msg (`sender`,`receiver`,`title`,`is_read`,`content`,`object_id`,`object_type`,`msg_type`,`create_time`) 
                    values ({$userinfo['UserID']},{$info[$i]['UserID']},'{$title}',2,'{$content}',{$id},1,2,'{$newtime}')";
            $res_log = DB::insert($sql);
            if(!$res_log){
                DB::rollback();
                return 7;
            }
        }
        DB::commit();
        return 1;
    }


    /**
     * @desc 提交企业认证
     * @param $userinfo
     * @param $data
     * @param $img
     * @return int
     */
    public function add_new_company($userinfo,$data,$img){
        DB::beginTransaction();
        //判断用户是否有申请加入企业待审核
        $sql = "select * from usersys where UserID = {$userinfo['UserID']} and State = 1";
        $user = DB::select($sql);
        if($user){
            $user = $this->object_array($user);
            if(!empty($user['companyID'])){
                return 2;
                DB::rollback();
            }
        }else{
            return 3;
            DB::rollback();
        }
        //判断是否申请加入企业
        $sql = "select * from pro_apply_join where user_id = {$userinfo['UserID']} and state = 1";
        $join = DB::select($sql);
        if($join){
            $join = $this->object_array($join)[0];
            if(!empty($join['Id'])){
                return 4;
                DB::rollback();
            }
        }
        //判断是否申请认证
        $sql = "select * from company_attestation where user_id = {$userinfo['UserID']} and state = 1";
        $com = DB::select($sql);
        if($com){
            $com = $this->object_array($com)[0];
            if(!empty($com['Id'])){
                return 5;
                DB::rollback();
            }
        }
        //上传营业执照
        if(!empty($img)){
            $oss = new Oss();
            $oss_upimg = $oss->ossup($img,'');
            if(isset($oss_upimg['license_img']['url'])){
                $data['license_img'] = $oss_upimg['license_img']['url'];
            }
        }
        //插入数据
        $time = date("Y-m-d h:i:s",time());
        $sql = "insert into company_attestation (`user_id`,`company_name`,`telnum`,`address`,`industry`,`company_no`,`license_img`,`state`,`create_time`) 
                values ({$userinfo['UserID']},'{$data['company_name']}','{$data['telnum']}','{$data['address']}','{$data['industry']}','{$data['company_no']}',
                '{$data['license_img']}',1,'{$time}')";
        $res = DB::insert($sql);
        if($res){
            DB::commit();
            return 1;
        }else{
            DB::rollback();
            return 7;
        }
    }

	/**
     * @desc 判断用户是否有提交申请加入/认证企业
     * @param $userid
     * @return int
     */
    public function check_user_join_state($userid){
        //判断是否已加入企业
        $sql = "select * from usersys where UserID = {$userid} and State = 1";
        $user = DB::select($sql);
        if($user){
            $user = $this->object_array($user);
            if(!empty($user['companyID'])){
                return 2;
            }
        }
        //判断是否申请加入企业
        $sql = "select * from pro_apply_join where user_id = {$userid} and state = 1 and `type` = 1";
        $join = DB::select($sql);
        if($join){
            $join = $this->object_array($join)[0];
            if(!empty($join['Id'])){
                return 3;
            }
        }
        //判断是否申请认证
        $sql = "select * from company_attestation where user_id = {$userid} and state = 1";
        $com = DB::select($sql);
        if($com){
            $com = $this->object_array($com)[0];
            if(!empty($com['Id'])){
                return 4;
            }
        }
        return 1;
    }

























    /**
     * @desc 格式化日期
     * @param $the_time
     * @return string
     */
    public function time_tran($the_time){
        $now_time = time();
        if($now_time<$the_time){
            $dur = $the_time-$now_time;
            if($dur < 60){
                return '剩余'.floor($dur / 1).'秒';
            }else {
                if ($dur < 3600) {
                    return '剩余'.floor($dur / 60) . '分钟';
                } else {
                    if ($dur < 86400) {
                        return '剩余'.floor($dur / 3600) . '小时';
                    } else {
                        if ($dur < 2592000) {
                            return '剩余'.floor($dur / 86400) . '天';
                        }else{
                            if($dur < 31536000){
                                return '剩余'.floor($dur / 2592000) . '个月';
                            }else{
                                return '剩余'.floor($dur / 31536000) . '年';
                            }
                        }
                    }
                }
            }
        }else{
            $dur = $now_time - $the_time;
            if($dur < 60){
                return floor($dur / 1).'秒前';
            }else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 2592000) {
                            return floor($dur / 86400) . '天前';
                        }else{
                            if($dur < 31536000){
                                return floor($dur / 2592000) . '个月前';
                            }else{
                                return floor($dur / 31536000) . '年前';
                            }
                        }
                    }
                }
            }
        }

    }




}